from PyQt5.QtWidgets import *
from pyqtgraph import QtCore, QtGui
from PyQt5.QtWidgets import QVBoxLayout, QWidget, QDialog, QPushButton, QMessageBox
from threading import Thread
import os
import configparser
import globalvar
global dict_instrumentgroup, dict_instrumentgrouprun
dict_instrumentgroup = {}
dict_instrumentgrouprun = {}
global list_instrumentgroup
# 策略文件名称
list_instrumentgroup=['main.csv','optional1','optional2','optional3','optional4','optional5','optional6','optional7','optional8','optional9','optional10']
readinstrumentgroupstaste = 1

global deleteButtonlist
deleteButtonlist = []

def CheckInstrumentIDInTable(InstrumentID):
    row_cnt = globalvar.ui.table_instrument.rowCount()  # 返回当前行数（尾部）
    for i in range(row_cnt):
            if globalvar.ui.table_instrument.item(i, 2).text() == InstrumentID:
                print(str(i))

                return True
            else:
                print(str(i))
    return False


# 去除过期的或重复的合约
def RemoveInvalidInstrument(filename1):
    grouplist = []
    with open(filename1, 'r') as f:
        for line in f:
            line = line.replace(',,', ',')
            if line[-1] == ',':
                line = line[:-1]
            if line[0] == ',':
                line = line[1:]
            grouplist = line.strip('\n').split(',')
            continue
    news_ids = []
    line2 = ""
    for InstrumentID in grouplist:
        if InstrumentID not in news_ids:
            if CheckInstrumentIDInTable(InstrumentID):
                news_ids.append(InstrumentID)
                if len(line2) > 0:
                    line2 = line2 + ',' + InstrumentID
                else:
                    line2 = InstrumentID
                with open(filename1, "w") as f:
                    f.write(line2)

#从文件读取合约组信息
def ReadInstrumentIDGroupInfo(filename):
    RemoveInvalidInstrument(filename)
    grouplist=[]
    with open(filename, 'r') as f:
        for line in f:
            grouplist = line.strip('\n').split(',')
    return len(grouplist)

def Function_Clicked_EditInstrumentID(rowid):
    button = globalvar.ui.MainWindow.sender()
    if button == False:
        return
    row = globalvar.ui.table_instrumentgroup.indexAt(button.pos()).row()
    if globalvar.DialogSetInstrumentState:
        return
    globalvar.DialogSetInstrumentState = True
    dlg = globalvar.ui.DialogEditInstrumentID(globalvar.ui.table_instrumentgroup.item(row, 1).text())
    dlg.setWindowTitle('编辑合约组：'+globalvar.ui.table_instrumentgroup.item(row, 1).text())
    dlg.show()
    screenRect = QApplication.desktop().screenGeometry()
    dlg.resize(0.58 * screenRect.width(), 0.60 * screenRect.height())
    # 居中窗口
    screen = QDesktopWidget().screenGeometry()
    size = dlg.geometry()
    dlg.move((screen.width() - size.width()) / 2,
                  (screen.height() - size.height()) / 2)
    dlg.exec_()

def Function_ScanInstrumentIDGroup():
        path = "instrumentgroup"
        ls = os.listdir(path)
        buttonid=0
        for i in ls:
            c_path = os.path.join(path, i)
            if os.path.isdir(c_path):
                print(c_path)
                globalvar.ui.ClearPath(c_path)
            else:
                file = os.path.splitext(c_path)
                filename, type = file
                if type == ".csv":
                    if c_path in dict_instrumentgroup:
                        if dict_instrumentgroup[c_path] != globalvar.ui.fileTime(c_path):
                            #修改了
                            pass
                    else:
                        try:
                            filenameini = c_path
                            filenameini = filenameini.replace('py', 'ini')
                            '''
                            #  实例化configParser对象
                            config = configparser.ConfigParser()
                            # -read读取ini文件
                            config.read(filenameini, encoding='utf-8')
                            if config.getint('setting', 'run') == 1:
                                dict_instrumentgrouprun[c_path] = 1
                            else:
                                dict_instrumentgrouprun[c_path] = 0
                            '''
                            dict_instrumentgroup[c_path] = globalvar.ui.fileTime(c_path)
                            # print("find Strategy file:", c_path,globalvar.ui.fileTime(c_path))
                            row_cnt = globalvar.ui.table_instrumentgroup.rowCount()  # 返回当前行数（尾部）
                            # print("列数：",row_cnt)
                            globalvar.ui.table_instrumentgroup.insertRow(row_cnt)  # 尾部插入一行新行表格
                            column_cnt = globalvar.ui.table_instrumentgroup.columnCount()  # 返回当前列数
                            # for column in range(column_cnt):
                            item = QTableWidgetItem(str(row_cnt + 1))
                            globalvar.ui.table_instrumentgroup.setItem(row_cnt, 0, item)
                            item = QTableWidgetItem(str(c_path))
                            globalvar.ui.table_instrumentgroup.setItem(row_cnt, 1, item)
                            item = QTableWidgetItem(str(ReadInstrumentIDGroupInfo(str(c_path))))
                            globalvar.ui.table_instrumentgroup.setItem(row_cnt, 2, item)
                            item = QTableWidgetItem('备注')
                            globalvar.ui.table_instrumentgroup.setItem(row_cnt, 3, item)

                            # buttonid="{} 设置合约".format(row_cnt)
                            # deleteButton = QPushButton("{} 设置合约".format(row_cnt))
                            deleteButton = QPushButton("编辑合约组"+str(i))
                            deleteButtonlist.append(deleteButton)
                            deleteButton.clicked.connect(Function_Clicked_EditInstrumentID)
                            buttonid = buttonid + 1
                            globalvar.ui.table_instrumentgroup.setCellWidget(row_cnt, 4, deleteButton)
                        except Exception as e:
                            print("Function_ScanInstrumentIDGroup Error:" + repr(e))